package com.zesionlee.server.exception

//import com.zesionlee.base.annotation.Slf4j2
//import com.zesionlee.base.annotation.Slf4j2.Companion.log
import com.zesionlee.server.result.Result
import io.swagger.v3.oas.annotations.Hidden
import jakarta.servlet.http.HttpServletRequest
import lombok.extern.java.Log
import lombok.extern.slf4j.Slf4j
import org.springframework.http.converter.HttpMessageNotReadableException
//import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.bind.MethodArgumentNotValidException
import  org.slf4j.Logger
import org.slf4j.LoggerFactory

@Slf4j
@RestControllerAdvice(basePackages = ["com.zesionlee.server"])
//@ControllerAdvice
//@Hidden
class ExceptionHandler() {

    private val log: Logger = LoggerFactory.getLogger(this::class.java)

    private fun insertErrorLog(request: HttpServletRequest, message: String) {
        log.error("调用接口 `${request.requestURI} 出错：${message}")
    }


    @ExceptionHandler(CustomException::class)
    fun handleCustomException(request: HttpServletRequest, exception: CustomException): Result<Unit> {
        insertErrorLog(request, exception.message.toString())
        return Result.error(exception.message!!)
    }


    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleArgException(request: HttpServletRequest, exception: MethodArgumentNotValidException): Result<Unit> {
        val message = exception.bindingResult.allErrors[0].defaultMessage.toString()
        insertErrorLog(request, message)
        return Result.error(message)
    }

//    @ExceptionHandler(PSQLException::class)
//    fun handlePSQLException(request: HttpServletRequest, exception: PSQLException): Result<String> {
//        val message = exception.message!!
//        insertErrorLog(request, message)
//        return Result.error("数据库查询错误")
//    }

    @ExceptionHandler(HttpMessageNotReadableException::class)
    fun handleHttpMessageNotReadableException(
        request: HttpServletRequest,
        exception: HttpMessageNotReadableException
    ): Result<Unit> {
        val message = exception.message!!
        insertErrorLog(request, message)
        return Result.error("参数错误！")
    }

    @ExceptionHandler(Exception::class)
    fun handleAllException(request: HttpServletRequest, exception: Exception): Result<Unit> {
        val message = exception.message!!
        insertErrorLog(request, message)
        return Result.error("参数错误！")
    }


}